package com.itheima.bos.web.action.base;

import com.itheima.bos.domain.Staff;
import com.itheima.bos.utils.PageBean;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by Mr.King on 2017/3/7.
 */
public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {

    public T model;
    @Override
    public T getModel() {
        return model;
    }

    //接收分页参数
    public int rows;
    public int page;
    public void setRows(int rows) {
        this.rows = rows;
    }
    public void setPage(int page) {
        this.page = page;
    }

    protected PageBean pageBean = new PageBean();
    protected DetachedCriteria criteria;


    //获得泛型的实例
    public BaseAction(){
        //获得父类类型
        ParameterizedType genericSuperClass = null;
        /*************解决shiro注解开发子类代理开发问题******************/
        Type type = this.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType){
            genericSuperClass = (ParameterizedType) type;
        }else {
            genericSuperClass = (ParameterizedType) this.getClass().getSuperclass().getGenericSuperclass();
        }
        /*************解决shiro注解开发子类代理开发问题******************/
        Type[] types = genericSuperClass.getActualTypeArguments();
        Class<T> clazz = (Class<T>) types[0];

        //离线条件查询
        criteria = criteria.forClass(clazz);
        pageBean.setDetachedCriteria(criteria);

        try {
            model = clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    //条件分页查询
    public void setPage (){
        pageBean.setCurrentPage(page);
        pageBean.setPageSize(rows);
    }

    //返回JSON数据格式
    public void toJSON(Object obj,String[] arr) throws IOException {
        //定义json数据格式
        JsonConfig config = new JsonConfig();
        config.setExcludes(arr);

        JSONObject jsonObject = null;
        JSONArray jsonArray = null;
        try {
            jsonObject = JSONObject.fromObject(obj,config);
        }catch (Exception e){
            jsonArray = JSONArray.fromObject(obj, config);
        }

        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/json;charset=utf-8");
        if (jsonObject != null){
            response.getWriter().print(jsonObject);
        }else {
            response.getWriter().print(jsonArray);
        }
    }
}
